<template>
	<view class="cart">
		<tabBar selectedIndex=1></tabBar>
		<view class="noData" v-if="list.length===0">
			<image :src="imgUrl+'cart-null.png'"></image>
			<view class="desc">快去填满你的购物车吧～</view>
			<view class="lookBtn" @tap="goIndex()">去逛逛</view>
		</view>
		
		<view v-if="list.length>0">
			<view class="good-panel" v-for="(item,index) in list" :key='index'>
				<cartGoods :goodItem='item' :refreshCount='refreshCountBool' @isChoose='isChoose'></cartGoods>
			</view>
			
			<view class="settlement_panle c-flex jc-between c-item-center">
				<view class="left c-flex c-item-center" @click="onAllChange">
					<image class="select" v-if="allBool" :src="imgUrl+'sele-Icon.png'"></image>
					<image class="select" v-if="!allBool" :src="imgUrl+'unsele-Icon.png'"></image>
					<text>全选</text>
				</view>
				<view class="right c-flex">
					<view class="fee c-flex c-item-center">
						<view class="c-flex c-item-center">
							<text>合计：</text>
							<text>￥{{goodsPriceTotal}}</text>
						</view>
						<!-- <view class="c-flex">
							含配送费 ￥{{freightAmount}}
							<view>?</view>
						</view> -->
					</view>
					<view class="settlement" @tap="settlementBtn">
						<text>结算</text>
						<text v-if='cartNum>0'>({{cartNum}})</text>
					</view>
				</view>
			</view>
		</view>
		

	</view>
</template>

<script>
	import {
		mapState,
		mapMutations,
		mapGetters
	} from 'vuex';
	import {
		toast,debounce
	} from '@/utils/utils.js'
	import cartGoods from '@/components/addCart/cartGoods.vue'
	export default {
		components: {
			cartGoods
		},
		data() {
			return {
				allBool: true,
				imgUrl: this.$API.IMG_URL + '/liquefied-mall/common/',
				list: [],
				refreshCountBool: false,
				goodsPriceTotal: 0,
				freightAmount: 0,
				cartNum:0,
				cartIds:''
			}
		},
		computed: {
			...mapGetters([
				'cartChooseStatus', 'cartChooseGood','cartCount','cartSeleCount','userSeleAddr'
			])
		},
		onLoad(options) {

			uni.setNavigationBarColor({
				backgroundColor: '#f9ead5',
				frontColor: '#000000'
			});
			uni.$on('getGood', (data) => {
				console.log('getGood', data.action)
				if (data.action === 'updateCart') {
					this.refreshCountBool = false;
					this.getCartList()
				}
			
			})
			
		},
		onUnload() {
			uni.$off('getGood')
		},
		onShow() {
			
			console.log('cartChooseStatus', this.cartChooseStatus)
			this.cartNum = this.cartSeleCount;
			this.getCartList();
		},
		methods: {
			...mapMutations(['setCartChooseStatus', 'setCartChooseGood','setCartNewData','setCartSeleCount']),
			calePrice() {
				this.goodsPriceTotal = 0;
				//this.freightAmount = 0;
				this.cartNum = 0;
				this.list.map(item => {
					if (item.selected) {
						this.goodsPriceTotal += item.lpgSkuEntity.price * item.saleCount;
						//this.freightAmount += item.lpgSkuEntity.freightAmount * item.saleCount;
						this.cartNum += item.saleCount;
					}
				})
				this.goodsPriceTotal = Number(this.goodsPriceTotal).toFixed(2)
				this.setCartSeleCount(this.cartNum)
				
			},
			settlementBtn:debounce(function(){
				let arr=[]
				this.list.map(item => {
					if (item.selected) {
						arr.push(item.id)
					}
				})
				const goodsIdArr=arr;
				if(arr.length===0) return
				this.cartIds = arr.toString();
				console.log(this.userSeleAddr.id)
				this.lpgUserId = this.userSeleAddr.id;
				this.lpgUserId
				this.$API.goSettlement({lpgUserId:this.lpgUserId,cartIds:this.cartIds}).then(res=>{
					uni.navigateTo({
						url:'/pages/client/sureOrder/sureOrder?data='+JSON.stringify(res)+'&cartIds='+this.cartIds+'&lpgUserId='+this.lpgUserId+'&goodsIdArr='+JSON.stringify(goodsIdArr)
					})
				})
			},500),
			goIndex(){
				uni.switchTab({
					url:"/pages/plat-menu/index"
				})
			},
			/**
			 * 是否全选
			 */
			onAllChange() {
				this.allBool = !this.allBool;
				this.setListStatus(this.allBool);
			},
			setListStatus(bl) {
				this.refreshCountBool = false;
				this.list.forEach(item => {
					item.selected = bl;
					
				})
				//保存购物车商品是否选中状态
				this.setCartChooseGood(this.list);
				this.calePrice();
				// uni.$emit('getGood', {
				// 	action: 'allChoose'
				// })
				//更新购物车选中的状态
				setTimeout(() => {
					this.refreshCountBool = true;
				}, 100);
				
			},
			getCartList() {
				const params = {}
				this.$API.getCartGoodsList(params).then(res => {

					let tmpArr =  res.list;
					let currCartList = this.cartChooseGood;
					
					//首次新加入购物车的商品
					if(currCartList.length===0){
						console.log(tmpArr,'=======0000============')
						tmpArr.forEach(item => {
							item['selected'] = true;
							
						})
						this.setCartChooseGood(tmpArr);
					}else{
						let result;
						let newGoods =tmpArr.filter((v) => !currCartList.some((val) => val.id === v.id))
						
						//新加入购物车的商品默认选中
						newGoods.forEach(item => {
							item['selected'] = true;
							
						})
						//没有新加入的商品时检查是否有移除的商品
						if(newGoods.length===0){
							result = this.removeExtraItems(res.list,currCartList,'id');
							console.log(result);
							
						}else{
							//有新加入的商品时维护到购物车列表
							result = [...currCartList,...newGoods];
							
						}
						
						result.forEach((item,idx)=>{
							item.saleCount = tmpArr[idx].saleCount;
						})
						
						this.setCartChooseGood(result);
					}
					
					
					
					console.log('list:',this.cartChooseGood)
					this.list = this.cartChooseGood;
					
					
					
					
					this.calePrice();
					setTimeout(() => {
						this.refreshCountBool = true;
					}, 400);



				}).catch(() => {

				});
			},
			removeExtraItems(arrayA, arrayB, key) {
			  const bKeys = new Set(arrayA.map(item => item[key]));
			 
			  arrayB = arrayB.filter(item => bKeys.has(item[key]));
			 
			  return arrayB;
			},
			isChoose(data) {
				console.log(this.list)
				console.log('是否选中：', data)

				
				this.list.map(item => {
					if (item.id == data.id) {
						item.selected = data.selected
						
					}
				})
				this.setCartChooseGood(this.list);
				this.allBool = this.list.every(item => {
					return item.selected == true;
				})
				this.calePrice();
				console.log('更新后的数据', this.list)

			}


		}
	}
</script>
<style>
	page {
		background: #F9F9F9;
	}
</style>
<style lang="scss" scoped>
	.cart {
		position: relative;
		padding-bottom: 220rpx;
		.good-panel {
			margin: 24rpx;
		}
		.noData{
			text-align: center;
			image{
				width: 328rpx;
				height: 328rpx;
				margin-top:270rpx;
			}
			.desc{
				font-family: PingFang-SC, PingFang-SC;
				font-weight: 500;
				font-size: 30rpx;
				color: #999999;
				margin: 40rpx 0;
			}
			.lookBtn{
				margin: 0 auto;
				width: 436rpx;
				height: 90rpx;
				background: linear-gradient( 180deg, #F18858 0%, #E86547 100%);
				border-radius: 45rpx;
				font-family: PingFang-SC, PingFang-SC;
				font-weight: 500;
				font-size: 30rpx;
				color: #FFFFFF;
				line-height: 90rpx;
				text-align: center;
			}
		}
		.settlement_panle {
			width: 100%;
			height: 130rpx;
			background: #FFFFFF;
			position: fixed;
			bottom: 128rpx;
			.left{
				.select {
					width: 38rpx;
					height: 38rpx;
					margin: 0 10rpx 0 28rpx;
				}
				text{
					ont-family: PingFang-SC, PingFang-SC;
					font-weight: 500;
					font-size: 24rpx;
					color: #333333;
					line-height: 30rpx;
				}
				
			}
			
			.right {
				.settlement {
					margin-right: 16rpx;
					width: 202rpx;
					height: 80rpx;
					background: #E86748;
					border-radius: 40rpx;
					text-align: center;

					text {
						font-family: PingFang-SC, PingFang-SC;
						font-weight: 500;
						font-size: 30rpx;
						color: #FFFFFF;
						line-height: 80rpx;
					}
				}

				.fee {
					margin-right: 20rpx;

					view:nth-child(1) {
						text:nth-child(1) {
							font-family: PingFang-SC, PingFang-SC;
							font-weight: 500;
							font-size: 28rpx;
							color: #333333;
							//line-height: 34rpx;
						}

						text:nth-child(2) {
							font-family: DINAlternate, DINAlternate;
							font-weight: bold;
							font-size: 40rpx;
							color: #F2270B;
							line-height: 48rpx;


						}
					}

					view:nth-child(2) {
						font-family: PingFang-SC, PingFang-SC;
						font-weight: 500;
						font-size: 22rpx;
						color: #6A6969;

						view {
							margin-left: 10rpx;
							border: 2rpx solid #6A6969;
							height: 30rpx;
							width: 30rpx;
							border-radius: 100%;
							text-align: center;
							line-height: 30rpx;
						}
					}
				}
			}
		}
	}
</style>